<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台（PHP版）
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | gitee下载：https://gitee.com/likeshop_gitee/likeadmin
// | github下载：https://github.com/likeshop-github/likeadmin
// | 访问官网：https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------

namespace app\api\logic;

use app\common\enum\YesNoEnum;
use app\common\logic\BaseLogic;
use app\common\model\article\Article;
use app\common\model\article\ArticleCate;
use app\common\model\article\ArticleCollect;
use app\common\model\article\Xiaoxi;
use app\common\model\user\User;
use app\common\model\user\UserAuth;

use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use EasyWeChat\OfficialAccount\Application;
use think\facade\Db;
/**
 * 文章逻辑
 * Class ArticleLogic
 * @package app\api\logic
 */
class ArticleLogic extends BaseLogic
{

    /**
     * @notes 文章详情
     * @param $articleId
     * @param $userId
     * @return array
     * @author 段誉
     * @date 2022/9/20 17:09
     */
    public static function detail($articleId, $userId)
    {
        // 文章详情
        $article = Article::getArticleDetailArr($articleId);
        // 关注状态
        $article['collect'] = ArticleCollect::isCollectArticle($userId, $articleId);

        return $article;
    }

    public static function xiaoxifa($postData) {
        $userlist =Db::name('user')->select()->toArray();

        for ($i = 0; $i < count($userlist); $i++) {  //循环所有用户
            if($userlist[$i]['dingyue'] != '' && $userlist[$i]['dingyue'] != null){
                $userlist[$i]['dingyue'] = explode(",", $userlist[$i]['dingyue']);
                for ($j = 0; $j < count($userlist[$i]['dingyue']); $j++) {
                    $dingyue = (new Xiaoxi())->where("id", "=", $userlist[$i]['dingyue'][$j])->findOrEmpty()->toArray();
                    if (strpos($postData['name'], $dingyue['name']) !== false) {
                        $xi = (new UserAuth())->where("id", "=", $userlist[$i]['id'])->value("openid");

                        self::template1($xi, $postData['name']);
                        break;
                    }
                }
            }
        }
    }

  /*  public static function dingyuexiaoxi($openid = '', $name = "")
    {
        $template_id = 'CXZUq0DSuPyo49Y96yohSfnyOIgTwaJcafPCJCS3O_w';
        $data = [
            'thing6' => $name,
            'thing7' => '盛悦科技',
        ];
        $res =self::template1($openid, $template_id, $data);
        print_r($res);
    }*/

    public static function template1($openid,$name)
    {


        $config = [
            'app_id' => 'wxaae9936c4891bea0',
            'secret' => 'a018f583ad80711396355269aee3ae71',
            'token' => 'guoyitong13145',
            'aes_key' => '' //明文模式下为空
        ];
        $app = new Application($config);
        $api = $app->getClient();
        $accessToken = $app->getAccessToken(); // 使用easywechat自带的方法,获取访问令牌
        $token = $accessToken->getToken(); // string
        $data = [];

        $data['thing2']['value'] = $name;
        $data['character_string8']['value'] = 'yao';

        $template = [
            'touser' => $openid,
            'template_id' => 'us9omVgOjXIkJHDNYwoLItdafZfu4L3ShqN5YFI9ke4',
            'url' => 'https://www.yaoyunxin.cn/mobile',
            'data' => $data,

        ];
        $template = json_encode($template, true);
        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $token;

        $result = self::posts($url, $template);

        if ($result['errcode'] == 0) {
            echo '发送成功';
        } else {
            echo '发送失败';


        }
    }
    public static function posts(string $url, $params, array $headers = [])
    {
        $headers[] = 'Content-type: application/json';
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $output = curl_exec($ch);
        curl_close($ch);

        return json_decode($output, true);
    }
    public static function template($openid, $template_id, $data, $url = '', $miniprogram = ['appid' => '', 'pagepath' => ''])
    {
        $config = [
            'app_id' => 'wxaae9936c4891bea0',
            'secret' => 'a018f583ad80711396355269aee3ae71',
            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',
        ];
        $app = new Application($config);
        return $app->template_message->send([
            'touser' => $openid,
            'template_id' => $template_id,
            'url' => $url,
            'miniprogram' => $miniprogram,
            'data' => $data,
        ]);
    }

    /**
     * @notes 加入收藏
     * @param $userId
     * @param $articleId
     * @author 段誉
     * @date 2022/9/20 16:52
     */
    public static function addCollect($articleId, $userId)
    {
        $where = ['user_id' => $userId, 'article_id' => $articleId];
        $collect = ArticleCollect::where($where)->findOrEmpty();
        if ($collect->isEmpty()) {
            ArticleCollect::create([
                'user_id' => $userId,
                'article_id' => $articleId,
                'status' => YesNoEnum::YES
            ]);
        } else {
            ArticleCollect::update([
                'id' => $collect['id'],
                'status' => YesNoEnum::YES
            ]);
        }
    }


    /**
     * @notes 取消收藏
     * @param $articleId
     * @param $userId
     * @author 段誉
     * @date 2022/9/20 16:59
     */
    public static function cancelCollect($articleId, $userId)
    {
        ArticleCollect::update(['status' => YesNoEnum::NO], [
            'user_id' => $userId,
            'article_id' => $articleId,
            'status' => YesNoEnum::YES
        ]);
    }


    /**
     * @notes 文章分类
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @author 段誉
     * @date 2022/9/23 14:11
     */
    public static function cate()
    {
        return ArticleCate::field('id,name')
            ->where('is_show', '=', 1)
            ->order(['sort' => 'desc', 'id' => 'desc'])
            ->select()->toArray();
    }

}